package com.bwhx.eruler.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.bwhx.eruler.bean.Buyer;
import com.bwhx.eruler.bean.Page;
import com.bwhx.eruler.bean.Ruler;
import com.bwhx.eruler.bean.Staff;
import com.bwhx.eruler.service.BuyerService;
import com.bwhx.eruler.service.RulerService;
import com.bwhx.eruler.service.StaffService;

import sun.security.util.Length;


@Controller
public class CangkuController extends BaseController {
	
	@Autowired
	RulerService rulerService;
	
	@Autowired
	BuyerService buyerService;
	
	@Autowired
	StaffService staffService;
	
	/**
	 * sn号为8位阿拉伯数字从 "16001800"开始，按照生成顺序向上加1
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/csharpclient.getSN.ashx",method={RequestMethod.POST})
	 public Map getSN(@RequestBody String device) {
		
		Map map = new HashMap();
		map.put("meg", "获取成功");
		map.put("msg", "获取成功");
		map.put("status", "1");
		log.info("============="+device+"====================");
		device = device.trim().replace(" ", "").replace("{", "").replace("}", "").split(":")[1];
		try{
			if(null!=device&&!"".equals(device)){
				
				String sn = rulerService.findUnusedSN(device);
				if(sn==null){
					sn = rulerService.insertSN(device);
				}
				if(sn=="-1"){
					map.put("meg", "6位SN已经用完！");
					map.put("msg", "6位SN已经用完！");
					map.put("status", "0");
				}else{
					map.put("sn", sn);
				}
			
			}else{
				map.put("meg", "请选择设备类型");
				map.put("msg", "请选择设备类型");
				map.put("status", "0");
			}
			
						
		}catch(Exception e){
			log.error(getTrace(e));
			map.put("meg", "获取失败！");
			map.put("msg", "获取失败！");
			map.put("status", "0");
		}
	    return map;  
	  }
	
	@ResponseBody
	@RequestMapping(value = "/csharpclient.inputRuler.ashx",method={RequestMethod.POST})
	 public Map inputRuler(@RequestBody Ruler r) {
		
		Map<Object, Object> map = new HashMap<Object,Object>();
		map.put("meg", "入库成功");
		map.put("msg", "入库成功");
		map.put("status", "1");

		try{
		
			
			String rsn = r.getRsn();
			
			if(rulerService.isRsnAvliable(rsn)){
				Ruler findByMAC = rulerService.findByMAC(r.getrMac());
				if( findByMAC!= null){
					map.put("meg", "入库失败！与"+findByMAC.getRsn()+"MAC地址重复");
					map.put("msg", "入库失败！与"+findByMAC.getRsn()+"MAC地址重复");
					map.put("status", "3");
				}else{
					r.setrState(3);  //已调试
					r.setrRukuTime(System.currentTimeMillis()/1000);
					rulerService.inputRuler(r);
				}
					
			}else{
				map.put("meg", "入库失败！您申请的key已经被他人使用，请重新申请 新的sn值");
				map.put("msg", "入库失败！您申请的key已经被他人使用，请重新申请 新的sn值");
				map.put("status", "2");
			}
				
		}catch(Exception e){
			log.error(getTrace(e));
			map.put("meg", "入库失败！");
			map.put("msg", "入库失败！");
			map.put("status", "0");
		}
	    return map;  
	  }
	
	
 	
	
	
	
	@ResponseBody 
	@RequestMapping(value = "/page.outputrulerlist.ashx")
	 public Map outputRulerList(Integer page,Integer rows,Ruler r,String startdate,String enddate) throws ParseException {
		
		log.info(page+"++++++++++page+++++++++++");
		log.info(rows+"++++++++++++rows+++++++++");
		log.info(r.getRsn()+"++++++++++++queryParams+++++++++");
		log.info(r.getrMac()+"++++++++++++queryParams+++++++++");
		log.info(startdate+"++++++++++++queryParams+++++++++");
		log.info(enddate+"++++++++++++queryParams+++++++++");
		 Long startdateLong = null;
		 Long enddateLong = null;
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		if(null!=startdate&&startdate.trim()!=""){
			Date date = sdf.parse(startdate);
		    startdateLong = date.getTime()/1000-1;
		}
		if(null!=enddate&&enddate.trim()!=""){
			Date enddateDate = sdf.parse(enddate);
		    enddateLong = enddateDate.getTime()/1000+60*60*24;
		}

		
		//每页的开始记录
        int start = (page-1)*rows;
        Page p = new Page(start,rows,r);
		Map map = new HashMap();
		try{
			List<Ruler> list = rulerService.list(p,startdateLong,enddateLong);
			Integer count = rulerService.count(r,startdateLong,enddateLong);
			log.info(list);
			log.info(count);
			
			map.put("total",count );//total键 存放总记录数，必须的  
			map.put("rows",list);//rows键 存放每页记录 list 
			
			
		}catch(Exception e){
			log.error(getTrace(e));
			map.put("meg", "失败！");
			map.put("msg", "失败！");
			map.put("status", "0");
		}
		
	    return map;  
	  }
	
	@ResponseBody 
	@RequestMapping(value = "/page.selleroutputrulerlist.ashx")
	 public Map selleroutputrulerlist(Integer page,Integer rows,Ruler r, HttpServletRequest request) {
		
		log.info(page+"++++++++++page+++++++++++");
		log.info(rows+"++++++++++++rows+++++++++");
		log.info(r.getRsn()+"++++++++++++queryParams+++++++++");
		
		//每页的开始记录
		Staff staff = (Staff) request.getSession().getAttribute("staff");
		
		if(!staff.getsLoginName().equals("admin")){
			r.setrSellerId(staff.getsId());
		}
		
        int start = (page-1)*rows;
        Page p = new Page(start,rows,r);
		Map map = new HashMap();
		try{
			
			List<Ruler> list = rulerService.list(p);
			Integer count = rulerService.count(r);
			log.info(list);
			log.info(count);
			
			map.put("total",count );//total键 存放总记录数，必须的  
			map.put("rows",list);//rows键 存放每页记录 list 
			for (Ruler ruler : list) {
				log.info(ruler);
			}
			
		}catch(Exception e){
			log.error(getTrace(e));
			map.put("meg", "失败！");
			map.put("msg", "失败！");
			map.put("status", "0");
		}
		
	    return map;  
	  }
	

	@RequestMapping(value = "/page.rdetails.ashx")
	 public ModelAndView OfflineOrderDetails(@RequestParam String rId){
		Ruler ruler = rulerService.get(rId);
		ModelAndView modelAndView = new ModelAndView("/outputruler/rdetails.jsp","r",ruler);
		if(ruler.getrBuyerId()!=null&&ruler.getrBuyerId()!=0){
			if(null==ruler.getrGoWhere()){
			}else if(0==ruler.getrGoWhere()){
				Staff staff = staffService.get(ruler.getrBuyerId());
				modelAndView.addObject("rstaff", staff);
			}else if(1==ruler.getrGoWhere()){
				Buyer buyer = buyerService.get(ruler.getrBuyerId());
				modelAndView.addObject("buyer", buyer);
			}
		}
		
	    return modelAndView;
		//return new ModelAndView("/outputruler/rdetails.jsp","r",ruler);
	  }
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	/*@ResponseBody 
	@RequestMapping(value = "/page.saveChuKuDan.ashx")
	public String saveChuKuDan(ChuKuDan chukudan) {
		try{
		
			chukudan.setSnsList(Arrays.asList(chukudan.getSns().split(",")));
			chukudan.setChukuTime(System.currentTimeMillis()/1000);
			rulerService.insertChuKuDan(chukudan);
			
			rulerService.update(chukudan);
			
			
		}catch(Exception e){
			log.error(getTrace(e));
			return "fail";
		}
		return "success";
	}*/
}
